package com.dylan.channel;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Logger;

public class NettyClient {
    private  static  Logger logger=Logger.getLogger(NettyClient.class.getName());
    public static void main(String[] args) {
        try {
            Selector selector=Selector.open();
            SocketChannel socketChannel=SocketChannel.open();
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_CONNECT );
            socketChannel.connect(new InetSocketAddress(8086));
            while (true){
                selector.select(3000);
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = keys.iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    if(key.isConnectable()){ //如果是连接事件
                        if(socketChannel.finishConnect()){
                            socketChannel.register(selector,SelectionKey.OP_READ);
                        }
                    }
                    if(key.isReadable()){
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        int read = channel.read(buffer);
                        if(read==-1){
                            channel.close();
                            key.cancel();
                            break;
                        }
                        buffer.flip();
                        logger.info("接受到服务端发过来的消息:"+new String(buffer.array(),StandardCharsets.UTF_8).trim());
                    }
                }
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
